;$(function() {
	/****************************************************************************************************
	* 					留资
	* 
	* **************************************************************************************************/

	var locationData = {
			cars: [{
					carid: 0,
					name: '车型'
			},{
					carid: 'B311',
					name: 'CS15'
			},{
					carid: 'S101',
					name: 'CS35'
			},{
					carid: 'S201',
					name: 'CS55',
					series_name: "CS55"
			},{
					carid: 'S301',
					name: 'CS75'
			},{
					carid: 'S401',
					name: 'CS95'
			},{
					carid: 'C201',
					name: '新逸动',
					series_name: "新逸动"
			},{
					carid: 'C211',
					name: '第二代逸动',
					series_name: "第二代逸动"
			},{
					carid: 'C202',
					name: '逸动XT'
			},{
					carid: 'B211',
					name: '悦翔V7'
			},{
					carid: 'V301',
					name: '凌轩MT'
			}],
			citys: [],
			chooses: [],
		},
		subData = {
			region_id_3: 0,
			region_id_3_name: '',
		};
	function setCar(cid, cname, cseries) {
		subData.car_series = cid;
		subData.car_name = cname;
		subData.carname = cname;
		subData.car_series_name = cseries;
		subData.car_brand = '2';
		subData.car_leave = '1';
	};
	// $("#carcode").change(function(){
		setCar('C212', '第二代逸动XT', '第二代逸动XT');
		getProvinces();//获取省份
	// });

	function getRequest(data, callback) {
		var urlparams = '',
			params = [];
		for(var k in data) {
			params.push(k + '=' + data[k]);
		}
		//加入时间戳
		params.push('_=' + Date.parse(new Date()));
		var url = (params.length > 0) ? caServer.dataurl + '&' + params.join('&') : caServer.dataurl;
		$.ajax({
			type: "get",
			url: url,
			async: true,
			dataType: 'jsonp',
			jsonp: "callback", //传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
			success: function(result) {
				if(typeof callback == 'function')
					callback(result);
			},
			error: function(e) {
				console.log('get data Error, E:', e);
			}
		});
	}
	//设置select
	function setSelect(params, callback) {
		var $sel = $(params.key);
		$sel.html('<option value="0">'+params.deftitle+'</option>')
		$.each(params.datalist, function(i, v) {
			$sel.append('<option value='+ v[params.valkey] +'>'+v[params.txtkey]+'</option>');
		});
		if (typeof callback == 'function') {
			$sel.change(function() {
				callback(this);
			});
		}		
	}
	function getProvinces() {
		function setProvinces(plist) {
			var params = {
				key: '#province',
				datalist: plist,
				deftitle: '请选择省份',
				valkey: 'regionCode',
				txtkey: 'regionName',
			}
			setSelect(params, function(sel) {
				var id = $(sel).val(),
					name = $(sel).find("option:selected").text();
				subData.region_id_1 = id;
				subData.region_id_1_name = name;
				getCitys(id);
				setSubmitBtnActive(false);
			});
		}
		getRequest({
			m: 'province',
			stype: 'jc_',
			groupCode: subData.car_series,
		}, setProvinces);
	}
	function getCitys(provinceId) {
		function setCitys(clist) {
			var params = {
				key: '#city',
				datalist: clist,
				deftitle: '请选择城市',
				valkey: 'regionCode',
				txtkey: 'regionName',
			}
			setSelect(params, function(sel) {
				var id = $(sel).val(),
					name = $(sel).find("option:selected").text();
				subData.region_id_2 = id;
				subData.region_id_2_name = name;
				getChooses(id);
				setSubmitBtnActive(false);
			});
		}
		getRequest({
			m: 'city',
			pcode: provinceId,
			stype: 'jc_',
			groupCode: subData.car_series,
		}, setCitys);
	}
	//经销商
	function getChoosesInfo(name) {
		for(var k in locationData.chooses) {
			if(locationData.chooses[k].dealerName == name) {
				return locationData.chooses[k];
			}
		}
		return 0;
	}
	function getChooses(cityId) {
		function setChooses(clist) {
			locationData.chooses = clist;
			var params = {
				key: '#choose',
				datalist: clist,
				deftitle: '请选择经销商',
				valkey: 'dealerId',
				txtkey: 'dealerName',
			}
			setSelect(params, function(sel) {
				var id = $(sel).val(),
					name = $(sel).find("option:selected").text();
				var info = getChoosesInfo(name);
					subData.dealer_id = info.dealerId;
					subData.dealer_code = info.dealerCode;
					subData.dealer_code_name = info.dealerName ;
					subData.dealer_brand = 1;
                // getDealer(id);
                setSubmitBtnActive(true);
            });
		}
		//http://e.changan.com.cn/changan_dealers/api.php?appkey=212C9F1F9C02A967352C0935DD9CDA20&m=dealers&stype=jc_&groupCode=S401&cityid=500100
		getRequest({
			m: 'dealers',
			cityid: cityId,
			stype: 'jc_',
			groupCode: subData.car_series,
		}, setChooses);
	}
    // function getDealer(cityId) {
    //     function setChooses(clist) {
    //         locationData.chooses = clist;
    //         var params = {
    //             key: '#dealer',
    //             datalist: clist,
    //             deftitle: '请选择经销商',
    //             valkey: 'dealerId',
    //             txtkey: 'dealerName',
    //         }
    //         setSelect(params, function(sel) {
    //             var id = $(sel).val(),
    //                 name = $(sel).find("option:selected").text();
    //             var info = getChoosesInfo(name);
    //             subData.dealer_id = info.dealerId;
    //             subData.dealer_code = info.dealerCode;
    //             subData.dealer_code_name = info.dealerName ;
    //             subData.dealer_brand = 1;
    //             setSubmitBtnActive(true);
    //         });
    //     }
    //     //http://e.changan.com.cn/changan_dealers/api.php?appkey=212C9F1F9C02A967352C0935DD9CDA20&m=dealers&stype=jc_&groupCode=S401&cityid=500100
    //     getRequest({
    //         m: 'dealers',
    //         cityid: cityId,
    //         stype: 'jc_',
    //         groupCode: subData.car_series,
    //     }, setChooses);
    // }
	function getCarsId(name) {
		for(var k in locationData.cars) {
			if(locationData.cars[k].name == name) {
				subData.carcode = locationData.cars[k].carid;
				return subData.carcode;
			}
		}
		return 0;
	}
	function getCars() {
		var list = [];
		$.each(locationData.cars, function(i, v) {
			list.push(v.name);
		});
	}
	function setSubmitBtnActive(key) {
		if (key == true) {
			$('#subscribe').addClass('active');
		} else {
			$('#subscribe').removeClass('active');
		}
	}
	
	/*//文本输入框功能
	var iExMethod = {
		showInputTxt: function($txtEle, key) {
			$txtEle.css('display', (key) ? '' : 'none');
		},
		iBlur: function($iEle, $txtEle, key) {
			var _self = this;

			_self.showInputTxt($txtEle, $iEle.val().length <= 0);
			_self.showWarring($txtEle, false);
		},
		inFocus: function($iEle, $txtEle) {
			var self = this;
			self.showInputTxt($txtEle, false);
			$iEle.focus();
		},
		showPick: function($iEle) {
			//显示下拉数据
			if($iEle.hasClass('selects')) {
				$iEle.click();
			}
		},
		showWarring: function($txtEle, key) {
			var $se = $txtEle.find('i');
			if(key) {
				$txtEle.addClass('must');
				$se.addClass('must');
			} else {
				$txtEle.removeClass('must');
				$se.removeClass('must');
			}
		},
		eventEntrance: function(e, $iEle, $txtEle) {
			var _data = e.data,
				self = this;
			switch(_data.eventType) {
				case 'txtClick':
					self.inFocus($iEle, $txtEle);
					self.showPick($iEle);
					self.showWarring($txtEle, false);
					break;
				case 'focus':
					self.showInputTxt($txtEle, false);
					break;
				case 'blur':
					self.iBlur($iEle, $txtEle, true);
					break;
				default:
			}
		},
		setValue: function($iEle, $txtEle, val) {
			var self = this;
			$iEle.val(val);
			self.showInputTxt($txtEle, false);

		},
		init: function($iEle, $txtEle) {
			var _self = this;
			$iEle.on('focus', {
				eventType: 'focus'
			}, function(e) {
				_self.eventEntrance(e, $iEle, $txtEle);
			});
			$iEle.on('blur', {
				eventType: 'blur'
			}, function(e) {
				_self.eventEntrance(e, $iEle, $txtEle);
			});
			$txtEle.on('click', {
				eventType: 'txtClick'
			}, function(e) {
				_self.eventEntrance(e, $iEle, $txtEle);
			});
		}
	}
	function inputEx() {
		$('.test_drive-box').find('input[type="text"]').each(function() {
			var $self = $(this),
				$txtEle = $self.siblings('span');

			iExMethod.init($self, $txtEle);
		});
	}
	inputEx();
*/
	//检查数据
	function checkData(data) {
//		$('.test_drive-box').find('input[type="text"]').each(function() {
//			var $self = $(this),
//				$txtEle = $self.siblings('span');
//			if($self.val().length <= 0) {
//				alert('请确认信息正确性！');
//				return false;
//			}
//		});
		if($('#user_name').val().length <= 0){
			alert("为了给您提供更好地服务，请输入正确的姓名！");
			return false;
		}
		var $self = $('#user_phone');
		var phoneno = $self.val();
		if(phoneno.length != 11) {
			alert("为了给您提供更好地服务，请输入正确的电话号码！");
			return false;
		}
		/*if($('.test_drive-box #selectCar').val() == 0){
			alert("为了给您提供更好地服务，请选择正确的车系！");
			return false;
		}*/
		if($('.test_drive-box #province').val() == 0){
			alert("为了给您提供更好地服务，请选择正确的省份！");
			return false;
		}
		if($('.test_drive-box #city').val() == 0){
			alert("为了给您提供更好地服务，请选择正确的城市！");
			return false;
		}
		if($('.test_drive-box #choose').val() == 0){
			alert("为了给您提供更好地服务，请选择正确的经销商！");
			return false;
		}
		return true;
	}

	//提交留资数据
	$('#subscribe').on('click', function() {
		if(!checkData(subData))
			return;
		var data = {
			op: 'try',
			aid: 437,
			name: $('#user_name').val(),
			mobile: $('#user_phone').val(),
		}
		subData = $.extend(subData, data);
		var pars = [];				
		for(var k in subData) {
			pars.push(k + '=' + subData[k]);
		}
		// var url = 'http://www.changan.com.cn/api.php?' + pars.join('&');
		var url = 'http://e.changan.com.cn/raeton_cc2017_5/api.php?' + pars.join('&');
		$.ajax({
			type: "get",
			url: url,
			async: true,
			//dataType: 'jsonp',
			success: function(result) {
				var robj = $.parseJSON(result);
				alert(robj.msg);
			},
			error: function(e) {
				console.log(e);
			}
		});
	});
})
